<?php

class Service_Curl {

	protected $_headers;
	protected $_user_agent;
	protected $_compression;
	protected $_cookie_file;
	protected $_proxy;

	public function __construct($cookies = TRUE, $cookie = '/tmp/cookies.txt', $compression = 'gzip', $proxy = '') {
		$this->_headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
		$this->_headers[] = 'Connection: Keep-Alive';
		$this->_headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
		$this->_user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
		$this->_compression = $compression;
		$this->_proxy = $proxy;
		$this->_cookies = $cookies;
		if ($this->_cookies == TRUE) {
			$this->cookie($cookie);
		}
	}

	public function cookie($cookie_file) {
		if (file_exists($cookie_file)) {
			$this->_cookie_file = $cookie_file;
		} else {
			fopen($cookie_file, 'w') or $this->error('The cookie file could not be opened. Make sure this directory has the correct permissions');
			$this->_cookie_file = $cookie_file;
			fclose($this->_cookie_file);
		}
	}

	public function get($url) {
		$url = str_replace("&amp;", '&', $url);

		$process = curl_init($url);
		curl_setopt($process, CURLOPT_HTTPHEADER, $this->_headers);
		curl_setopt($process, CURLOPT_HEADER, 0);
		curl_setopt($process, CURLOPT_USERAGENT, $this->_user_agent);
		if ($this->_cookies == TRUE)
			curl_setopt($process, CURLOPT_COOKIEFILE, $this->_cookie_file);
		if ($this->_cookies == TRUE)
			curl_setopt($process, CURLOPT_COOKIEJAR, $this->_cookie_file);
		curl_setopt($process, CURLOPT_ENCODING, $this->_compression);
		curl_setopt($process, CURLOPT_TIMEOUT, 30);
		curl_setopt($process, CURLOPT_HTTPGET, true);


		if ($this->_proxy)
			curl_setopt($process, CURLOPT_PROXY, $this->_proxy);
		curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
		$return = curl_exec($process);
		curl_close($process);
		return $return;
	}

	public function post($url, $data) {
		$process = curl_init($url);
		curl_setopt($process, CURLOPT_HTTPHEADER, $this->_headers);
		curl_setopt($process, CURLOPT_HEADER, 1);
		curl_setopt($process, CURLOPT_USERAGENT, $this->_user_agent);
		if ($this->_cookies == TRUE)
			curl_setopt($process, CURLOPT_COOKIEFILE, $this->_cookie_file);
		if ($this->_cookies == TRUE)
			curl_setopt($process, CURLOPT_COOKIEJAR, $this->_cookie_file);
		curl_setopt($process, CURLOPT_ENCODING, $this->_compression);
		curl_setopt($process, CURLOPT_TIMEOUT, 30);
		if ($this->_proxy)
			curl_setopt($process, CURLOPT_PROXY, $this->_proxy);
		curl_setopt($process, CURLOPT_POSTFIELDS, $data);
		curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($process, CURLOPT_POST, 1);
		$return = curl_exec($process);
		curl_close($process);
		return $return;
	}

	public function error($error) {
		throw new Exception($error);
	}

}
